package libs

import (
	"exercise/application/yiran/app"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
	"os"
	"path/filepath"
	"time"
)

func NewLogger(filename string, debug bool) *zap.Logger {
	writeSyncer := getLogWriter(filename, debug)
	encoder := getEncoder()
	//caller := zap.AddCaller()
	//开启开发者模式，也就是stacktrace
	//development := zap.Development()
	//logger := zap.New(core, caller, development)
	core := zapcore.NewCore(encoder, writeSyncer, zapcore.DebugLevel)
	logger := zap.New(core)
	return logger
}

// 文件位置
func getLogWriter(filename string, debug bool) zapcore.WriteSyncer {

	if filename == "" {
		filename = TimestampToDate(time.Now().Unix(), "02") + ".log"
	}

	//文件路径
	path := filepath.Join(app.YiRanRuntimeLogs, TimestampToDate(time.Now().Unix(), "200601"), filename)

	hook := lumberjack.Logger{
		Filename:   path, //文件路径
		MaxSize:    10,   //每个日志文件的大小，单位：M
		MaxBackups: 30,   //每个日志文件的备份的个数
		MaxAge:     7,    //每个日志文件的保留时长,单位：天
		Compress:   true,
	}

	var info = []zapcore.WriteSyncer{zapcore.AddSync(&hook)}
	if debug {
		//日志同步更新到控制台
		info = append(info, zapcore.AddSync(os.Stdout))
	}
	return zapcore.NewMultiWriteSyncer(info...)
}

// 文件类型
func getEncoder() zapcore.Encoder {
	customTimeEncoder := func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
		enc.AppendString(t.Format("2006-01-02 15:04:05.000"))
	}

	customCallerEncoder := func(caller zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder) {
		enc.AppendString("[" + caller.TrimmedPath() + "]")
	}

	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = customTimeEncoder
	encoderConfig.TimeKey = "time"
	encoderConfig.EncodeCaller = customCallerEncoder
	encoderConfig.LineEnding = "\n"
	return zapcore.NewJSONEncoder(encoderConfig)
}

// LoggerInfo 打印日志
func LoggerInfo(data interface{}, filename string) {
	NewLogger(filename, false).Info("记录日志：", zap.Any("打印的数据：", data))
}

// LoggerError 错误日志
func LoggerError(data interface{}) {
	NewLogger("error.log", false).Error("异常日志：", zap.Any("打印的数据：", data))
}

// LoggerSysInfo 系统日志
func LoggerSysInfo(data interface{}) {
	filename := TimestampToDate(time.Now().Unix(), "02") + "_request.log"
	NewLogger(filename, false).Info("发起请求：", zap.Any("请求的参数：", data))
}
